<template>
  <div class="main-container">
    <!-- 条件搜索 -->
    <Condition>
      <!-- 算法名称 -->
      <div class="condition-item">
        <span class="condition-label">参数名称</span>
        <el-input 
          class="condition-input" 
          v-model="conditionForm.name" 
          placeholder="请输入参数名称"
          @keyup.enter.native="getList"
          @change="getList" 
        />
      </div>
    </Condition>
    <!-- 数据表格部分 -->
    <div class="data-show">
      <!-- 头部操作按钮部分 -->
      <div class="data-actions">
        <span class="aniTxtBtn action" @click="linkToCreate">新增参数</span>
      </div>
      <!-- 底下表格 -->
      <div class="data-table">
        <el-table border v-loading="conditionForm.loading" :data="datas" stripe show-header>
          <el-table-column label="序号" align="center" type="index" width="100" />
          <el-table-column label="名称" align="center" prop="name"  />
          <el-table-column label="创建人" align="center" prop="createBy">
            <template #default="scope">
              {{ scope.row.createBy ? scope.row.createBy : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime" />
          <el-table-column label="参数描述" align="center" show-overflow-tooltip prop="des">
            <template #default="scope">
              {{ scope.row.des ? scope.row.des : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="导出文件类型" align="center" show-overflow-tooltip prop="exportFileType">
            <template #default="scope">
              {{ scope.row.exportFileType ? scope.row.exportFileType : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="嵌入率" align="center" show-overflow-tooltip prop="embedRate"  />
          <el-table-column label="操作" align="center" width="200" fit>
            <template #default="scope">
              <div class="table-actions">
                <button class="aniTxtBtn blue" @click="linkToEdit(scope.row)">编辑</button>
                <button class="aniTxtBtn red" @click="delItem(scope.row)">删除</button>
              </div>
            </template>
          </el-table-column>
          <!-- 没有数据时显示 -->
          <template #empty>
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </template>
        </el-table>
      </div>
      <Pagination 
        v-show="conditionForm.totalRow > 0" 
        :total="conditionForm.totalRow"
        v-model:page="conditionForm.pageNumber"
        v-model:limit="conditionForm.pageSize"
        @pagination="pageChange" 
      />
    </div>
  </div>
</template>
<script setup>
import Condition from '@/components/common/Condition.vue';
import Pagination from '@/components/common/Pagination';
import { useRouter } from 'vue-router';
import { ref, computed, onActivated } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as parameterApi from '@/api/parameter.js';


// ============> data
const router = useRouter();
// 搜索条件表单项
const conditionForm = ref({
  loading: false,
  name: '',
  saveName: '',
  // 页条数
  pageSize: 10,
  // 当前页
  pageNumber: 1,
  // 总条数
  totalRow: 0,
  // 总页数
  totalPage: 0
});

const datas = ref([]);

// ============> computed
const getShow = computed(() => {
  return function (v, k, arr, returnKey) {
    let obj = arr.find((item) => item[k] === v);
    let res = obj ? obj[returnKey] : "--";
    return res;
  };
});

// ============> methods
// 重置上方的搜索条件
function resetCondition(){
  conditionForm.value.name = conditionForm.value.name != conditionForm.value.saveName ? conditionForm.value.saveName : conditionForm.value.name;
}
// 设置上方的搜索条件
function setCondition(){
  conditionForm.value.saveName = conditionForm.value.name;
}
function getList(){
  conditionForm.value.loading = true;
  const { name, pageSize, pageNumber } = conditionForm.value;
  parameterApi.getParameterList({name, pageSize, pageNumber})
    .then(res => {
      datas.value = res.records && Array.isArray(res.records) ? res.records : [];
      initDatas();
      setCondition();
      conditionForm.value.pageNumber = +res.pageNumber;
      conditionForm.value.pageSize = +res.pageSize;
      conditionForm.value.totalRow = +res.totalRow;
      conditionForm.value.totalPage = +res.totalPage;
      conditionForm.value.loading= false;
    })
    .catch(err => {
      conditionForm.value.loading = false;
      console.log(err)
      resetCondition();
    })
}
function initDatas(){
  if (Array.isArray(datas.value) && datas.value.length > 0){
    datas.value.forEach(item => {
      item.delFlag = false;
    })
  }
}
// 分页触发事件
function pageChange(e){
  // { page, limit }
  conditionForm.value.pageSize = e.limit;
  conditionForm.value.pageNumber = e.page;
  getList();
}
function linkToCreate(){
  router.push({ name: 'parameterCreate' });
}
function linkToEdit(item){
  router.push({ name: 'parameterCreate', query: { id: item.id} });
}
function delItem(item){
  if (item.delFlag) {
    ElMessage.warning('当前参数正在删除，请稍后再试');
    return;
  }
  ElMessageBox.confirm('您是否确认删除此参数？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(() => {
      item.delFlag = true;
      parameterApi.delParameter({id: item.id})
        .then(res => {
          ElMessage.success('删除参数成功！');
          item.delFlag = false;
          getList();
        })
        .catch(err => {
          console.log(err);
          item.delFlag = false;
          // let msg = err.msg || err.message || '删除参数失败，请稍后重试或联系管理员';
          // ElMessage.error(msg);
        })
    })
    .catch(() => {})
}
// onMounted(() => {
//   getList();
// });

onActivated(() => {
  getList();
});
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .action {
    width: 80px;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-text-hover);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
</style>